#!/bin/bash
# This is not a benchmark, instead it is responsible for running
# multiple benchmarks simultaneously to measure potential
# interference
###SHELLPACK preamble multi-bench 0

cd $SHELLPACK_TOPLEVEL
###SHELLPACK init_only_start
	# Check benchmark is supported for parallel use
	for MULTI_TEST in $MULTI_TESTS; do
		case $MULTI_TEST in
		kernbench)
			echo -n "Supported: kernbench"
			MULTI_SHUTDOWN=$MULTI_SHUTDOWN_KERNBENCH
			;;
		netperf-*)
			echo -n "Supported: netperf"
			MULTI_SHUTDOWN="$MULTI_SHUTDOWN_NETPERF"
			;;
		tbench4)
			echo -n "Supported: tbench4"
			MULTI_SHUTDOWN="$MULTI_SHUTDOWN_TBENCH"
			;;
		*)
			die "Unknown benchmark $MULTI_TEST for running under multi"
			;;
		esac
		if [ "$MULTI_SHUTDOWN" = "yes" ]; then
			echo " (run until shutdown)"
		else
			echo " (run until end)"
		fi
	done

	# Run installations
	for MULTI_TEST in $MULTI_TESTS; do
		echo Installing test $MULTI_TEST
		export INSTALL_ONLY=yes
		./bin/run-single-test.sh $MULTI_TEST
		if [ $? -ne 0 ]; then
			die "Installation step failed for $MULTI_TEST"
		fi
	done
###SHELLPACK init_only_end

declare -a PIDS
PIDINDEX=0
rm -f $LOGDIR_RESULTS/multi.list
for MULTI_TEST in $MULTI_TESTS; do
	echo Starting $MULTI_TEST
	echo $MULTI_TEST >> $LOGDIR_RESULTS/multi.list
	./bin/run-single-test.sh $MULTI_TEST &> $LOGDIR_RESULTS/output-$MULTI_TEST.log &
	PIDS[$PIDINDEX]=$!
	PIDINDEX=$((PIDINDEX+1))
done

echo

PIDINDEX=0
for MULTI_TEST in $MULTI_TESTS; do
	case $MULTI_TEST in
	kernbench)
		echo Waiting on $MULTI_TEST to complete
		wait_on_pid_exit ${PIDS[$PIDINDEX]}
		;;
	netperf-*)
		if [ "$MULTI_SHUTDOWN_NETPERF" = "yes" ]; then
			touch /tmp/mmtests-shutdown-netperf
		fi
		echo Waiting on $MULTI_TEST to complete
		wait_on_pid_exit ${PIDS[$PIDINDEX]}
		;;
	tbench4)
		if [ "$MULTI_SHUTDOWN_TBENCH" = "yes" ]; then
			TBENCH_PID=`cat /tmp/mmtests-tbench.pid`
			echo Sending SIGINT to tbench pid $TBENCH_PID
			kill -HUP $TBENCH_PID
		fi
		echo Waiting on controller to exit
		wait_on_pid_exit ${PIDS[$PIDINDEX]}
		;;
	*)
		die "Unknown benchmark $MULTI_TEST for running under multi"
		;;
	esac
	PIDINDEX=$((PIDINDEX+1))
done

exit $RETVAL
